/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAL;

import BE.Category;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Zalan
 */
public class CategoryDBManager {
     private final DBConnectionManager cm;
     
     private static CategoryDBManager instance = null;

    public static CategoryDBManager getInstance() throws IOException {
      
       if(instance == null)
       {
           instance = new CategoryDBManager();
       }
       return instance;
    }
    
    private CategoryDBManager() throws IOException
    {
        cm = DBConnectionManager.getInstance();
    }
    
    private Category getOneCategory(ResultSet rs) throws SQLException
    {
        int categoryId = rs.getInt("ID");
        String categoryName = rs.getString("Category");

        Category cat = new Category(categoryId, categoryName);
        return cat;
    }

    /**
     * @param categoryId
     * @return
     * @throws SQLException
     */
    public Category getById(int categoryId) throws SQLException
    {
        try (Connection con = cm.getConnection())
        {
            String sql = "SELECT * FROM Category WHERE ID = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1, categoryId);

            ResultSet rs = ps.executeQuery();
            if (rs.next())
            {
                return getOneCategory(rs);
            }
        }
        return null;
    }
    
      public Category getByName(String categoryName) throws SQLException
    {
        try (Connection con = cm.getConnection())
        {
            String sql = "SELECT * FROM Category WHERE Name = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, categoryName);

            ResultSet rs = ps.executeQuery();
            if (rs.next())
            {
                return getOneCategory(rs);
            }
        }
        return null;
    }
    
     
     
}
